import React, { Component, createRef } from 'react';
import { Form, Input, Button, message } from 'antd';
import { MobileOutlined, LockOutlined, KeyOutlined } from '@ant-design/icons';
import Captcha from "../../components/Captcha"
// 导入请求资源
import url from "../../config/url"
import req from "../../http/req"
import { withRouter } from "react-router-dom"

class Moblielogin extends Component {
  constructor(props){
    super(props)
    this.capRef = createRef()
    this.formRef = createRef()
  }
  // 成员属性存储定时器(t),成员属性是属于实例化的对象，通过实例对象.属性调用
  t = null
  state = {
    // 倒计时时长
    time: 60,
    // 用于标记是否已经完成短信的获取
    // 如果没有获取到短信，则就不会发送ajax请求进行后端验证
    sentCode: false,
    // 用来指定按钮是否可以内点击
    enabled: true,
  }
  render() {
    return (
      <div>
        <Form
        ref={this.formRef}
        name="normal_login"
        className="login-form"
        initialValues={{
          remember: true,
        }}
        onFinish={this.onFinish}
      >
        <Form.Item
          name="mobile"
          rules={[
            {
              required: true,
              message: '请输入手机号',
            },
          ]}
        >
          <Input prefix={<MobileOutlined className="site-form-item-icon" />} placeholder="手机号" maxLength="11" />
        </Form.Item>
        <Form.Item
          name="captcha"
          rules={[
            {
              required: true,
              message: '请输入图形验证码!',
            },
          ]}
        >
          <div>
            <Input
              prefix={<KeyOutlined className="site-form-item-icon" />}
              type="captcha"
              placeholder="请输入图形验证码" style={{width: "70%", marginRight: "7px"}}/>
              <Captcha h={32} w={96} setKey={this.getKey} ref={this.capRef}/>
          </div>
        </Form.Item>
        <Form.Item
          name="code"
          rules={[
            {
              required: true,
              message: '请输入短信验证码!',
            },
          ]}
        >
          <div>
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="text"
              maxLength="6"
              placeholder="请输入短信验证码" style={{width: "60%", marginRight: "7px"}}/>
              <Button type="primary" onClick={this.sendCode} disabled={!this.state.enabled} className="login-form-button" style={{width: "95px", height: "38px", marginRight: "7px"}}>
                {this.state.enabled ? "获取短信" : `重新获取(${this.state.time})`}
              </Button>
          </div>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button" block disabled={!this.state.sentCode}>
            登录
          </Button>
        </Form.Item>
      </Form>
      </div>
    );
  }
  onFinish = (values) => {
    let { code, mobile } = values
    let params = { mobile, code, requestId: this.state.requestId }
    req.post(url.MobileLogin,params).then(ret => {
      if(ret.data.errNo === 0){
        message.success("登录成功！", 2, () => {
          this.props.history.push("/dashboard")
        })
      }else{
        // 短信发送失败
        message.error(ret.data.errText, 2, () => {
          this.capRef.current.loadCaptcha()
        })
      }
    })
  };
  // 获取验证码key值的方法
  getKey = (key) => {
    this.setState({
      key
    })
  }
  // 获取短信验证码按钮功能
  sendCode = () => {
    // 倒计时什么时候开始（在发送短信后倒计时）
    // 验证图像验证码---发送短信
    // 拿到表单中输入框的值
    let { mobile, captcha } = this.formRef.current.getFieldsValue()
    if (/^1[3-9]\d{9}$/.test(mobile) && captcha) {
      req.post(url.VerifyCaptcha, { captcha, key: this.state.key}).then((res) => {
        if(res.data.errNo === 0){
          let token = res.data.context.token
          // 发短信
          req.post(url.SendCode, {mobile,token,type: 0}).then((ret) => {
            if(ret.data.errNo === 0){
              // 保存requestId
              this.setState({
                requestId: ret.data.requestId,
                sentCode: true
              })
              message.success("短信发送成功")
              this.timedown()
            }else{
              // 短信发送失败
              message.error(res.data.errText, 2, () => {
                this.capRef.current.loadCaptcha()
              })
            }
          })
        }else{
          message.error(res.data.errText, 2, () => {
            // 刷新验证码
            this.capRef.current.loadCaptcha()
          })
        }
      })
    } else {
      // 提示用户错误
      message.error("请输入合法的手机号和图形验证码")
    }
    // 测试倒计时功能
    // this.timedown()
  }
  // 倒计时
  timedown = () => {
    if (this.state.time === 0) {
      // 倒计时已经结束,重置时间,按钮可以被点击
      this.setState({
        time: 60,
        enabled: true
      })
    } else {
      // 倒计时没结束
      this.setState({
        time: this.state.time - 1,
        enabled: false
      })
      // 自调用
      this.t = setTimeout(() => {
        this.timedown()
      },1000)
    }
  }
  // 清理副作用（网络请求，定时器，巨耗资源的，事件监听）
  componentWillUnmount() {
    clearTimeout(this.t)
  }
}

export default withRouter(Moblielogin);
